package net.gyapp.markim.module.contact;

import android.Manifest;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.easyder.wrapper.base.adapter.ViewHelper;
import com.easyder.wrapper.base.listener.OnViewHelper;
import com.easyder.wrapper.base.view.WrapperStatusFragment;
import com.easyder.wrapper.core.model.BaseVo;
import com.easyder.wrapper.core.scheduler.Task;
import com.easyder.wrapper.core.scheduler.TaskScheduler;
import com.gyf.barlibrary.ImmersionBar;
import com.luck.picture.lib.permissions.RxPermissions;

import net.gyapp.markim.ApiConfig;
import net.gyapp.markim.R;
import net.gyapp.markim.WrapperApplication;
import net.gyapp.markim.core.ImHelper;
import net.gyapp.markim.core.ImManager;
import net.gyapp.markim.core.entity.GroupEntity;
import net.gyapp.markim.core.entity.MemberEntity;
import net.gyapp.markim.module.basic.MainActivity;
import net.gyapp.markim.module.basic.base.CommonPresenter;
import net.gyapp.markim.module.basic.event.AccountChanged;
import net.gyapp.markim.module.basic.event.AccountIml;
import net.gyapp.markim.module.basic.event.ResponseChanged;
import net.gyapp.markim.module.basic.event.ResponseIml;
import net.gyapp.markim.module.basic.event.TabChanged;
import net.gyapp.markim.module.collect.UserIntroduceActivity;
import net.gyapp.markim.module.contact.adapter.ContactsAdapter;
import net.gyapp.markim.module.contact.vo.ContactHeaderEntity;
import net.gyapp.markim.module.contact.vo.NewFrinedsVo;
import net.gyapp.markim.module.message.ConversationActivity;
import net.gyapp.markim.module.mine.QrScanActivity;
import net.gyapp.markim.utils.CommonTools;
import net.gyapp.markim.widget.SlideBar;
import net.gyapp.markim.widget.WrapperPopWindow;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import me.winds.widget.autolayout.utils.AutoUtils;
import me.winds.widget.cluster.refresh.NestedRefreshLayout;


/**
 * Auther:  winds
 * Data:    2018/2/27
 * Version: 1.0
 * Desc:    首页
 */


public class ContactsFragment extends WrapperStatusFragment<CommonPresenter> implements NestedRefreshLayout.OnRefreshListener {

    @BindView(R.id.mNestedRefreshLayout)
    NestedRefreshLayout mNestedRefreshLayout;
    @BindView(R.id.mRecyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.mSlideBar)
    SlideBar mSlideBar;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.status_bar_view)
    View statusBarView;

    ContactsAdapter adapter;
    WrapperPopWindow popupWindow;

    public static ContactsFragment newInstance() {
        return new ContactsFragment();
    }

    @Override
    public int getViewLayout() {
        return R.layout.fragment_contact;
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        ImmersionBar.with(this).init();
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        ImmersionBar.with(this).statusBarView(statusBarView).init();

        mNestedRefreshLayout.setOnRefreshListener(this);

        adapter = new ContactsAdapter();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(_mActivity));
        mRecyclerView.setAdapter(adapter);
        adapter.addHeaderView(getInfoView());
        mSlideBar.setOnTouchingLetterChangedListener(new SlideBar.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                if (s.equals("搜索")) {
                    mRecyclerView.scrollToPosition(0);
                } else {
                    int letterPosition = adapter.getLetterPosition(s);
                    if (letterPosition != -1) {
                        mRecyclerView.scrollToPosition(letterPosition + adapter.getHeaderLayoutCount());
                    }
                }
            }
        });

        mRecyclerView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
                MultiItemEntity item = adapter.getItem(position);
                if (item instanceof MemberEntity) {
                    startActivity(UserIntroduceActivity.getIntent(_mActivity, (MemberEntity) item));
                } else if (item instanceof GroupEntity) {
                    startActivity(ConversationActivity.getIntent(_mActivity, ImHelper.generateConversation((GroupEntity) item)));
                }
            }
        });
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        getContactData();
    }

    @Override
    protected void loadData(Bundle savedInstanceState) {
        getNewFriend();
    }

    @Override
    public void showContentView(String url, BaseVo dataVo) {
        super.showContentView(url, dataVo);
        if (url.contains(ApiConfig.API_GET_NEW_USER_FRIENDS)) {
            processNewFriend((NewFrinedsVo) dataVo);
        }
    }

    @Override
    protected boolean isLazyLoad() {
        return true;
    }

    @OnClick({R.id.iv_add})
    public void click(View view) {
        switch (view.getId()) {
            case R.id.iv_add:
                showFunctionPop((View) view.getParent());
                break;
        }
    }

    @Override
    public void onRefresh() {
        ImManager.getInstance().retryAutoLogin();
    }

    public void endRefresh() {
        if(mNestedRefreshLayout != null) {
            mNestedRefreshLayout.refreshFinish();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void responseChanged(ResponseChanged changed) {
        if (changed.sign == ResponseIml.SIGN_PROCESS_LOGIN_RESPONSE_SUCCESS) {
            getContactData();
            getNewFriend();
            endRefresh();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void accountChanged(AccountChanged changed) {
        if(changed.sign == AccountIml.ACCOUNT_CONTACT_INFO_CHANGED || changed.sign == AccountIml.ACCOUNT_CONTACT_QUIT_GROUP) { //名称或其他发生变化  刷新
            getContactData();
            getNewFriend();
            endRefresh();
        }
    }

    @Subscribe
    public void tabChanged(TabChanged changed) {
        if(WrapperApplication.isLogin()) {
            getNewFriend();
            endRefresh();
//            if (changed.sign == 1) {
//                ImManager.getInstance().retryAutoLogin();
//            }
        }
    }

    private void getContactData() {
        TaskScheduler.execute(new Task<List<MultiItemEntity>>() {
            @Override
            public List<MultiItemEntity> doInBackground() throws InterruptedException {
                List<MultiItemEntity> list = new ArrayList<>();
                List<GroupEntity> groupList = ImHelper.getGroupList();
                if (groupList != null && groupList.size() > 0) {
                    list.add(new ContactHeaderEntity("群聊", "群聊", ContactsAdapter.TYPE_CONTACT_HEADER));
                    list.addAll(groupList);
                }
                List<MemberEntity> friendList = ImHelper.getFriendList();
                if (friendList != null && friendList.size() > 0) {
                    for (int i = 0; i < friendList.size(); i++) { //获取首字母
                        MemberEntity entity = friendList.get(i);
                        entity.firstLetter = CommonTools.getLetter(entity.nick).toUpperCase();
                    }
                    adapter.sort(friendList); //排序

                    //添加头部
                    ContactHeaderEntity entity = new ContactHeaderEntity(friendList.get(0).firstLetter, friendList.get(0).firstLetter, ContactsAdapter.TYPE_CONTACT_HEADER);
                    list.add(entity);
                    for (int i = 0; i < friendList.size(); i++) {
                        MemberEntity item = friendList.get(i);
                        if (!item.firstLetter.equalsIgnoreCase(entity.firstLetter)) {
                            entity = new ContactHeaderEntity(item.firstLetter, item.firstLetter, ContactsAdapter.TYPE_CONTACT_HEADER);
                            list.add(entity);
                        }
                        list.add(item);
                    }

                }

                return list;
            }

            @Override
            public void onSuccess(List<MultiItemEntity> result) {
                adapter.setNewData(result);
            }
        });
    }

    private View getInfoView() {
        return getHelperView(mRecyclerView, R.layout.header_contact, new OnViewHelper() {
            @Override
            public void help(ViewHelper helper) {
                helper.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        switch (v.getId()) {
                            case R.id.layout_new_friend:
                                startActivity(NewFriendsActivity.getIntent(_mActivity));
                                break;
                            case R.id.layout_find_group:
                                startActivity(GroupAddActivity.getIntent(_mActivity));
                                break;
                            case R.id.layout_onion_service:
                                contactService();
                                break;
                            case R.id.layout_input:
                                startActivity(ContactSearchActivity.getIntent(_mActivity));
                                break;
                        }
                    }
                }, R.id.layout_new_friend, R.id.layout_find_group, R.id.layout_onion_service, R.id.layout_input);
            }
        });
    }

    private void getNewFriend() {
        presenter.setNeedDialog(false);
        presenter.postData(ApiConfig.API_GET_NEW_USER_FRIENDS, NewFrinedsVo.class);
    }

    private void processNewFriend(NewFrinedsVo dataVo) {
        if (dataVo.newUserFriends != null && dataVo.newUserFriends.size() > 0) {
            setNewFriendCount(dataVo.newUserFriends.size());
        } else {
            setNewFriendCount(0);
        }
    }

    private void setNewFriendCount(int count) {
        LinearLayout layout = adapter.getHeaderLayout();
        if (layout != null) {
            View view = layout.findViewById(R.id.tv_new_friend_num);
            if (view != null && view instanceof TextView) {
                if (count > 0) {
                    ((TextView) view).setText(String.valueOf(count));
                    view.setVisibility(View.VISIBLE);
                } else {
                    view.setVisibility(View.GONE);
                }
            }
        }
        setBadgeText(count);
    }

    private void setBadgeText(int count) {
        if (_mActivity != null && _mActivity instanceof MainActivity) {
            ((MainActivity) _mActivity).setBedgeText(1, count);
        }
    }

    private void showFunctionPop(View view) {
        popupWindow = new WrapperPopWindow.PopupWindowBuilder(getActivity())
                .setView(getHelperView(null, R.layout.pop_msg_fun, new OnViewHelper() {
                    @Override
                    public void help(ViewHelper helper) {
                        helper.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                switch (v.getId()) {
                                    case R.id.layout_scan:
                                        checkCameraPermission();
                                        break;
                                    case R.id.layout_add_friend:
                                        startActivity(ContactAddActivity.getIntent(_mActivity));
                                        break;
                                    case R.id.layout_add_group:
                                        startActivity(GroupAddActivity.getIntent(_mActivity));
                                        break;
                                    case R.id.layout_pop_parent:
                                        popupWindow.dissmiss();
                                        break;
                                }
                                popupWindow.dissmiss();
                            }
                        }, R.id.layout_scan, R.id.layout_add_friend, R.id.layout_add_group, R.id.layout_pop_parent);
                    }
                }))
                .size(AutoUtils.getPercentWidthSize(395), AutoUtils.getPercentHeightSize(512))
                .create().showAsDropDown(view, AutoUtils.getPercentWidthSize(700), 2);
    }

    private void checkCameraPermission() {
        new RxPermissions(_mActivity).request(Manifest.permission.CAMERA)
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Boolean aBoolean) {
                        if (!aBoolean) {
                            showToast("权限被拒绝");
                        }
                        onPermissionGain(aBoolean);
                    }

                    @Override
                    public void onError(Throwable e) {
                        showToast("申请权限出错");
                        onPermissionGain(false);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void onPermissionGain(Boolean aBoolean) {
        if (aBoolean) {
            startActivity(QrScanActivity.getIntent(_mActivity));
        }
    }

    private void contactService() {
        startActivity(ConversationActivity.getIntent(_mActivity, ImHelper.generateServiceConversation()));
    }


}
